import pymysql
import urllib.request
import json
from datetime import date, datetime, timedelta

def get_price_by_id(fund_id):
    headers = {
        "token": "atTPd9c8sA"
    }
    req = urllib.request.Request(url="https://api.doctorxiong.club/v1/fund/detail?code=" + fund_id + "&startDate=2021-05-14", headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    fund_info = json.loads(response)["data"]
    if "netWorth" not in fund_info.keys():
        return 0
    return float(fund_info["netWorth"])

db = pymysql.connect(host="114.115.160.16", user="root", password="123456Aa!", database="fund")
cursor = db.cursor()

sql = "select * from api_timing"
cursor.execute(sql)
for data in cursor.fetchall():
    timing_id = data[0]
    user_id = data[1]
    fund_id = data[2]
    money = data[3]
    date = data[4]
    number = data[5]
    span = data[6]
    '''
    if span == 0:   # 每周
        today = datetime.today().isoweekday()
        if today != date + 1:
            continue
    elif span == 1: # 每两周
        if number == 0: # 这周不定投
            sql = "update api_timing set number=1 where id=%d" % (timing_id)
            cursor.execute(sql)
            continue
        else:
            sql = "update api_timing set number=0 where id=%d" % (timing_id)
            cursor.execute(sql)
            today = datetime.today().isoweekday()
            if today != date + 1:
                continue
    elif span == 2:  # 每月
        now = date.today().day  # 今天是几号
        if now != date:
            continue
    '''
    tmp_sql = "select money from api_user where openid='%s'" % (user_id)
    cursor.execute(tmp_sql)
    haved_money = cursor.fetchall()[0][0]
    if haved_money < money:
        cursor.execute("select fund_name from api_fund where fund_id='%s'" % (fund_id))
        fund_name = cursor.fetchall()[0][0]
        cursor.execute("select max(id) from api_remind")
        max_id = cursor.fetchall()[0][0]
        if max_id == None:
            max_id = 1
        else:
            max_id += 1
        tmp_sql = "insert into api_remind values(%d,'%s','%s',%d,'%s',%d,'%s')" % (max_id, user_id, fund_name, 0, datetime.now().__format__("%Y-%m-%d %H:%M:%S"), 3, fund_id)
        cursor.execute(tmp_sql)
        continue
    else:
        # user
        tmp_sql = "update api_user set money=%f where openid='%s'" % (haved_money - money, user_id)
        cursor.execute(tmp_sql)

    price = get_price_by_id(fund_id)  # 当前净值
    number = money / price

    # check
    cursor.execute("select max(id) from api_check")
    max_id = cursor.fetchall()[0][0]
    if max_id == None:
        max_id = 1
    else:
        max_id += 1
    tmp_sql = "insert into api_check values(%d,'%s','%s',%f,%f,'%s',2,1)" % (
    max_id, user_id, fund_id, number, money, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    cursor.execute(tmp_sql)

    # hold
    tmp_sql = "select * from api_hold where user_id='%s' and fund_id='%s'" % (user_id, fund_id)
    cursor.execute(tmp_sql)
    holds = cursor.fetchall()
    cursor.execute("select max(id) from api_hold")
    max_id = cursor.fetchall()[0][0]
    if max_id == None:
        max_id = 1
    else:
        max_id += 1
    if len(holds) == 0:
        tmp_sql = "insert into api_hold values(%d,'%s','%s',%f,%f)" % (max_id, user_id, fund_id, money, number)
        cursor.execute(tmp_sql)
    else:
        haved_money = holds[0][3]
        haved_number = holds[0][4]
        tmp_sql = "update api_hold set cost=%f,number=%f where user_id='%s' and fund_id='%s'" % (
        haved_money + money, haved_number + number, user_id, fund_id)
        cursor.execute(tmp_sql)
db.commit()
print("定投完成!!")
